package com.hb.trade.api.im.chat.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.enums.RoleSignEnum;
import com.hb.core.pojo.project.proj.dto.ProjectBaseInfo;
import com.hb.trade.api.im.chat.manager.TradeLayImUser;
import com.hb.trade.api.im.chat.service.TradeImChatService;
import com.hb.trade.client.project.SectionClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.LayuiResponseDto;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.user.layim.LayImData;
import org.fzzn.core.model.user.layim.LayImGroup;
import org.fzzn.core.model.user.layim.LayImUser;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.IdUtil;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Version(1.0)
@Api(tags = {"layim即时通讯"})
@RequestMapping("/{version}")
@RestController
public class LayimUserController {

    protected final SectionClient sectionClient;
    protected final TradeImChatService tradeImChatService;

    public LayimUserController(SectionClient sectionClient,
                               TradeImChatService tradeImChatService) {
        this.sectionClient = sectionClient;
        this.tradeImChatService = tradeImChatService;
    }

    /**
     * 获取指定标段的群成员列表
     *
     * @param sectionId 标段ID
     * @return
     */
    @ApiOperation(value = "获取指定标段的群成员列表", notes = "获取指定标段的群成员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段Id", dataTypeClass = Long.class)
    })
    @PostMapping("/layim/group/info")
    public LayuiResponseDto groupInfo(Long sectionId) {
        if (sectionId == null) {
            return ResultUtil.layData(0, MsgEnum.NULL_RESULT.msg(), 0, null);
        }

        JSONObject data = JSONUtil.createObj();

        User agencyUser = tradeImChatService.getAgencyUser(sectionId);
        if (agencyUser == null) {
            return ResultUtil.layData(-1, "获取群成员失败", 0, null);
        }
        TradeLayImUser tradeLayImUser = new TradeLayImUser(agencyUser);
        data.putOpt("owner", tradeLayImUser);

        // 查询群成员
        List<User> users = tradeImChatService.listGroupMembers(sectionId);
        if (CollUtil.isEmpty(users)) {
            return ResultUtil.layData(-1, "获取群成员失败", 0, null);
        }

        List<LayImUser> members = CollUtil.list(false);
        for (User user : users) {
            members.add(new TradeLayImUser(user));
        }
        members.add(tradeLayImUser);
        data.putOpt("list", members);

        return ResultUtil.layData(0, "", 0, data);
    }

    /**
     * 获取layim好友列表面板数据
     * 指定标段ID下的投标人/代理机构信息
     *
     * @param sectionId 标段ID
     * @return
     */
    @ApiOperation(value = "获取layim好友列表面板", notes = "获取layim好友列表面板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段Id", dataTypeClass = Long.class)
    })
    @PostMapping("/layim/user/mine")
    public LayuiResponseDto mine(Long sectionId) {
        if (sectionId == null) {
            return ResultUtil.layData(-1, "[sectionId]不能为空, 必须指定标段ID", 0, null);
        }

        // 验证该标段的代理机构跟当前登录用户是否是同一个人
        User agencyUser = tradeImChatService.getAgencyUser(sectionId);
        if (agencyUser == null) {
            return ResultUtil.layData(-1, "代理机构信息获取失败", 0, null);
        }

        // 指定标段下的所有投标人列表
        List<User> bidders = tradeImChatService.listGroupMembers(sectionId);
        if (CollUtil.isEmpty(bidders)) {
            return ResultUtil.layData(-1, "未能获取投标人信息", 0, null);
        }

        // 判断当前登录用户角色
        JSONObject extInfo = ShiroUtil.getExtInfo();
        Integer roleSign = extInfo.getInt("roleSign");
        RoleSignEnum roleSignEnum = Enums.of(RoleSignEnum.class, roleSign);

        // 组装layim数据对象
        LayImData data = new LayImData();

        // 组装好友列表
        List<LayImUser> friends = CollUtil.list(false);

        // 好友默认分组 start
        LayImGroup friendGroup = LayImGroup.builder()
                .id(IdUtil.getId())
                .build();

        switch (roleSignEnum) {
            /* ************************************************************* */
            /*       招标人或代理机构登录时, 好友列表为当前参与该标段的投标人列表        */
            /*       群组列表为当前登录用户与所有参与该标段的所有投标人                */
            /* ************************************************************* */
            case TENDEREE: // 招标人/采购人
            case AGENCY: //代理机构
                // 代理机构个人信息
                data.setMine(new TradeLayImUser(agencyUser, true));
                friendGroup.setGroupname("投标人");

                friends = CollUtil.list(false);
                for (User user : bidders) {
                    friends.add(new TradeLayImUser(user));
                }
                break;
            /* ************************************************************* */
            /*        投标人/采购人登录时, 好友列表只有代理机构自己                  */
            /*        群组列表为当前登录用户与所有参与该标段的所有投标人               */
            /* ************************************************************* */
            case BIDDER: // 投标人/供应商
                friendGroup.setGroupname("招标人/代理机构");
                // 投标人个人信息
                User bidder = CollUtil.findOne(bidders, (item) -> item.getId().equals(ShiroUtil.getUserId()));
                data.setMine(new TradeLayImUser(bidder, true));
                // 查询该标段的代理机构用户信息
                friends.add(new TradeLayImUser(agencyUser));
            default:
        }
        friendGroup.setList(friends);
        data.setFriend(CollUtil.list(false, friendGroup));
        // 好友默认分组 end

        /* ************************************************************* */
        /*                不管什么角色, 群组信息为同一数据                     */
        /*                20220228, 去除群聊功能                           */
        /* ************************************************************* */
        // 群组信息 start
/*        List<LayImGroup> groups = CollUtil.list(false);

        Message<ProjectBaseInfo> info = sectionClient.projectBaseInfo(sectionId);
        ProjectBaseInfo baseInfo = info.getData();
        LayImGroup layImGroup = LayImGroup.builder()
                .id(sectionId)
                .groupname(baseInfo.getProjectName() + "群聊啊")
                .avatar("https://ddzb-trading.oss-cn-beijing.aliyuncs.com/nbcpa427fad090614273bc77adeb90dd3f37.jpeg")
                .build();

        Object groupData = groupInfo(sectionId).getData();
        List<LayImUser> imUsers = ((JSONObject) groupData).getJSONArray("list").toList(LayImUser.class);

        layImGroup.setList(imUsers);

        groups.add(layImGroup);
        data.setGroup(groups);*/
        // 群组信息 end

        return ResultUtil.layData(0, "", 0, data);
    }

}
